/**
 * 评论状态 composable
 * 从状态管理模块获取评论状态选项
 */
import { computed } from 'vue'
import { useStateStore } from '@/stores/state'
import { ModuleType } from '@/types/state'

export function useCommentStates() {
  const stateStore = useStateStore()

  // 获取评论状态列表
  const commentStates = computed(() => {
    return stateStore.getStatesByModule(ModuleType.COMMENT)
  })

  // 获取启用的评论状态
  const enabledStates = computed(() => {
    return commentStates.value.filter(state => state.is_enabled)
  })

  // 获取可见的评论状态
  const visibleStates = computed(() => {
    return commentStates.value.filter(state => state.is_visible)
  })

  // 获取默认状态
  const defaultState = computed(() => {
    return commentStates.value.find(state => state.is_default) || commentStates.value[0]
  })

  // 获取状态选项（用于下拉框）- 只返回启用且可见的状态
  const statusOptions = computed(() => {
    return enabledStates.value.filter(state => state.is_visible).map(state => ({
      value: state.code,
      label: state.name,
      color: state.color,
      icon: state.icon,
      disabled: false  // 因为是启用的状态，所以都不禁用
    }))
  })

  // 根据代码获取状态
  const getStateByCode = (code: string) => {
    return commentStates.value.find(state => state.code === code)
  }

  // 根据代码获取状态名称
  const getStateName = (code: string) => {
    const state = getStateByCode(code)
    return state?.name || code
  }

  // 根据代码获取状态颜色
  const getStateColor = (code: string) => {
    const state = getStateByCode(code)
    return state?.color || '#909399'
  }

  // 检查状态代码是否有效
  const isValidState = (code: string) => {
    return enabledStates.value.some(state => state.code === code)
  }

  // 检查评论是否已删除（兼容is_deleted字段）
  const isDeleted = (comment: { status?: string; is_deleted?: boolean }) => {
    if (comment.status) {
      return comment.status === 'deleted'
    }
    return comment.is_deleted || false
  }

  // 检查评论是否可见（排除已删除和已隐藏）
  const isVisible = (comment: { status?: string; is_deleted?: boolean }) => {
    if (comment.status) {
      return comment.status !== 'deleted' && comment.status !== 'hidden'
    }
    return !comment.is_deleted
  }

  // 加载状态数据
  const loadStates = async () => {
    await stateStore.fetchModuleStates(ModuleType.COMMENT)
  }

  return {
    commentStates,
    enabledStates,
    visibleStates,
    defaultState,
    statusOptions,
    getStateByCode,
    getStateName,
    getStateColor,
    isValidState,
    isDeleted,
    isVisible,
    loadStates
  }
}

